package com.wtx.atguigu.nio;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;

/**
 * @description: 使用一个buffer拷贝文件: 利用buffer的双向性
 * @author: wtx
 * @createDate: 2020/6/8
 */
public class NioFileChannel03 {

    public static void main(String[] args) throws IOException {

        FileInputStream fileInputStream01 = new FileInputStream("file01.txt");
        FileChannel channel01 = fileInputStream01.getChannel();

        FileOutputStream fileOutputStream02 = new FileOutputStream("file02.txt");
        FileChannel channel02 = fileOutputStream02.getChannel();

        ByteBuffer byteBuffer = ByteBuffer.allocate(512);

        while (true){
            /*public final Buffer clear() {
                position = 0;
                limit = capacity;
                mark = -1;
                return this;
            }
            * */
            //如果不重置, 在第一次flip, write之后, position==limit, 之后每次循环得到的read==0
            byteBuffer.clear();  //重置四个标记属性
            int read = channel01.read(byteBuffer);
            if (read==-1)   //读完
                break;
            byteBuffer.flip();
            channel02.write(byteBuffer);
        }

        fileInputStream01.close();
        fileOutputStream02.close();
    }
}
